package cn.kbyue.security.security;

import cn.kbyue.security.utils.Result;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

/**
 * 登录失败处理类
 *
 * @author xl
 * @date 2020/4/19 15:04
 */
@Slf4j
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

    /**
     * 用户登录失败的返回
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        Result<Object> error = Result.error("用户名或密码错误");
        //        // 用户名或密码错误
        //        if (exception instanceof BadCredentialsException || exception instanceof UsernameNotFoundException) {
        //            log.info("【登录失败】" + exception.getMessage());
        //            error = Result.error("用户名或密码错误");
        //        }
        //        // 用户被冻结
        //        else
        if (exception instanceof LockedException) {
            log.info("【登录失败】" + exception.getMessage());
            error = Result.error("账户已被锁定，请联系管理员");
        } else if (exception instanceof AccountExpiredException) {
            // 账户过期
            log.info("【登录失败】" + exception.getMessage());
            error = Result.error("账户已过期");
        } else if (exception instanceof DisabledException) {
            // 账户被禁用
            log.info("【登录失败】" + exception.getMessage());
            error = Result.error("账户被禁用，请联系管理员");
        } else if (exception instanceof AuthenticationServiceException) {
            log.info("【登录失败】" + exception.getMessage());
            error = Result.error(exception.getMessage());
        }
        Result.responseResult(response, error);
    }
}

